<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>计数案例-父子通信</title>
</head>

<body>
  <script src="/js/vue.js"></script>
  <div id="app">
    <!-- 父向子传递数据的时候通过 props  properties： 子组件通过props接收父组件传递的数据 父组件通v-bind 传递数据-->
    <p>{{counter}}</p>

    <!-- 子向父传递数据的时候通过 自定义事件 $emit事件 发射  子组件通过$emit 向父组件发送自定义事件 父组件通过v-on监听事件接收数据 -->
    <cpn :child-counter="counter" @change="changeTotal"></cpn>
  </div>

  <!-- 1. 创建模板 -->
  <template id="cpnT">
    <div>
      <button @click="increase">+</button>
      <button @click="decrease">-</button>
    </div>
  </template>

  <script>
    // 创建子组件对象
    const cpn = {
      template: `#cpnT`,
      data() {
        return {
          dCounter: this.childCounter
        }
      },
      props: {
        childCounter: Number
      },
      methods: {
        increase() {
          this.dCounter++
          this.$emit("change", this.dCounter)
        },
        decrease() {
          this.dCounter--
          this.$emit("change", this.dCounter)
        }
      }
    }


    let app = new Vue({
      el: "#app",
      data: {
        counter: 0
      },
      components: {
        cpn
      },
      methods: {
        changeTotal(value){
          this.counter = value
        }
      }
    })
  </script>
</body>

</html>